package org.mozhu.mboot.core.web.sitemesh;

import org.mozhu.mboot.core.web.freemarker.FreeMarkerMVCAutoConfiguration;
import org.mozhu.mboot.core.web.freemarker.FreeMarkerStaticModelRegistry;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import javax.servlet.Servlet;

/**
 * 主要解决和SiteMesh整合时，SiteMesh forward过来的请求得不到渲染的问题，比如无法找到layout.ftl等
 * 如果不和SiteMesh整合，不需要配置这个Configuration
 *
 * @author ZhangPei
 */
@Configuration
@ConditionalOnClass({Servlet.class, FreeMarkerConfigurer.class})
@AutoConfigureAfter(FreeMarkerMVCAutoConfiguration.class)
public class FreeMarker4SiteMeshConfiguration {

    @Bean("freeMarker4SiteMeshViewResolver")
    public FreeMarkerViewResolver freeMarker4SiteMeshViewResolver(FreeMarkerViewResolver freeMarkerViewResolver, FreeMarkerProperties properties, FreeMarkerStaticModelRegistry freeMarkerStaticModelRegistry) {
        FreeMarkerViewResolver viewResolver = new FreeMarkerViewResolver();
        properties.applyToMvcViewResolver(viewResolver);
        viewResolver.setAttributesMap(freeMarkerStaticModelRegistry.getStaticModels());
        if (properties.isExposeSpringMacroHelpers()) {
            // request里会有SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE，这里就不用再暴露了，否则会报异常
            viewResolver.setExposeSpringMacroHelpers(false);
        }
        return viewResolver;
    }
}
